import TodoHeader from './components/TodoHeader'
import TodoMain from './components/TodoMain'
import TodoFooter from './components/TodoFooter'
import './styles/base.css'
import './styles/index.css'
import React, { useState, useEffect } from 'react'
export const Context = React.createContext()
const { Provider } = Context
function useTodos() {
  const [list, setList] = useState(() => {
    return JSON.parse(localStorage.getItem('todoList')) || []
  })
  //将各项存到本地储存
  useEffect(() => {
    localStorage.setItem('todoList', JSON.stringify(list))
  }, [list])
  //删除项
  const delList = (id) => {
    setList(list.filter((item) => item.id !== id))
  }
  //添加项
  const addList = (name) => {
    setList([
      {
        id: Date.now(),
        name,
        done: false,
      },
      ...list,
    ])
  }
  //切换项的完成状态
  const changeDone = (id) => {
    setList(
      list.map((item) => {
        if (item.id === id) {
          return {
            ...item,
            done: !item.done,
          }
        } else {
          return item
        }
      })
    )
  }
  //修改项的name
  const reviseList = (id, name) => {
    setList(
      list.map((item) => {
        if (item.id === id) {
          return {
            ...item,
            name,
          }
        } else {
          return item
        }
      })
    )
  }
  //清除已完成项
  const clearCompleted = () => {
    setList(list.filter((item) => item.done === false))
  }
  return {
    list,
    delList,
    addList,
    changeDone,
    reviseList,
    clearCompleted,
  }
}
const App = () => {
  //设置底部中间状态栏的选择
  const [type, setType] = useState('All')
  const { list, delList, addList, changeDone, reviseList, clearCompleted } =
    useTodos()
  return (
    <Provider value={{ delList, changeDone, reviseList }}>
      <section className="todoapp">
        <TodoHeader addList={addList} />
        <TodoMain list={list} type={type} />
        <TodoFooter
          list={list}
          type={type}
          setType={setType}
          clearCompleted={clearCompleted}
        />
      </section>
    </Provider>
  )
}

export default App
